﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace MyLib
{
    /// <summary>
    /// 管理器服务器上代表一个 FPS游戏服务器实例
    /// 
    /// 工作在 FPSServerMgr 上下文下
    /// 
    /// 如何识别 Http协议和Tcp协议的服务器
    /// 需要双通道通信
    /// </summary>
    public class FPSServerInfo
    {
        public enum State
        {
            NotInit,
            Init,
            Used,
            Closed,
        }
        public State state = State.NotInit;
        public TcpNetConnect fpsConnect;
        public FPSServerMgr mgr;
        public MMFPSRoomInfo fpsRoomInfo;

        public FPSProtocol.LocalInfo localInfo;
        public FPSRoom usedRoom
        {
            get;
            private set;
        }
        public string GetHash()
        {
            if(state != State.NotInit)
            {
                return localInfo.GetHash();
            }
            return String.Empty;
        }
        /// <summary>
        /// 一个服务器的连接数据
        /// 尝试工作再Room 所在的线程 还是FPSServerMgr 所在线程
        /// 在两个逻辑对象之间通信
        /// </summary>
        /// <param name="packet"></param>
        public void HandleMsg(KBEngine.Packet packet)
        {
            LogHelper.Log2("FPSServer:HandleMsg:"+packet.protoBody);
            var tp = packet.protoBody.GetType();
            if(tp == typeof(MMFPSRoomInfo))
            {
                var roomInfo = packet.protoBody as MMFPSRoomInfo;
                if (roomInfo.Cmd == "ServerStart")
                {
                    fpsRoomInfo = roomInfo;
                    localInfo = new FPSProtocol.LocalInfo()
                    {
                        localIp = roomInfo.Ip,
                        localPort = roomInfo.Port,
                    };
                    state = State.Init;
                    mgr.AddFreeServer(this);

                    LogHelper.Log2("ServerStart:"+roomInfo);
                    //反馈
                    var gc = MMFPSRoomInfo.CreateBuilder();
                    gc.Cmd = "OK";
                    fpsConnect.SendPacketAck(gc, packet.flowId); 
                }
            }
        }

        /// <summary>
        /// FPSMgr 线程下
        /// 网络连接断开
        /// </summary>
        public void OnClose()
        {
            //移除自己
            mgr.RemoveFPSServer(this);
            //通知FPSRoom关闭
            usedRoom.OnClose();
            state = State.Closed;
        }

        public async Task SetUsedRoom(FPSRoom r)
        {
            await mgr._messageQueue;
            usedRoom = r;
        }

    }
}
